package com.findMoneyGame.pages.achievement {

	import flash.display.DisplayObjectContainer;
	import flash.events.Event;

	import com.findMoneyGame.pages.achievement.AchievedNotification;
	import com.findMoneyGame.models.User;
	import com.findMoneyGame.models.Model;

	public class AchievementWatcher {
		
		private static var achievements = [
			['Новичок', 1, 150, 3, 2, 50],
			['Любитель', 3, 300, 5, 4, 150],
			['Эксперт', 5, 600, 10, 6, 300],
			['Мастер', 10, 1200, 20, 8, 600],
			['Гранд', 20, 2000, 50, 10, 1500]
		];
		private var _stage : DisplayObjectContainer;


		private function get user () { return User.getInst(); }


		public function AchievementWatcher (stage : DisplayObjectContainer) {
			_stage = stage;
			user.addEventListener(Model.UPDATE, userUpdate);
			check();
		}

		private function userUpdate (e : Event) { check(); }
		private function check () {
			user.removeEventListener(Model.UPDATE, userUpdate);
			for (var i = 0; i < achievements.length; i++) {
				var achievedValue = achieved(i);
				if (achievedValue) {
					user.achievement = i;
					user.addMoney(reward(achievements[i]));
					achievedNotification(achievements[i]);
				}
			}
			user.addEventListener(Model.UPDATE, userUpdate);
		}
		private function achieved (index : int) : Boolean {
			var achievement = achievements[index];
			var result = 
				user.achievement < index && 
				user.season >= season(achievement) &&
				user.moneyCount >= balance(achievement) &&
				user.fastCompletedLevelCount >= fastCompletedLevels(achievement) &&
				user.improvementsCount >= improvementsCount(achievement);
			return result;
		}
		private function name (achievement : Array) : String { return achievement[0]; }

		private function season (achievement : Array) : int { return achievement[1]; }

		private function balance (achievement : Array) : int { return achievement[2]; }

		private function fastCompletedLevels (achievement : Array) : int { return achievement[3]; }

		private function improvementsCount (achievement : Array) : int { return achievement[4]; }

		private function reward (achievement : Array) : int { return achievement[5]; }

		private function achievedNotification (achievement : Array) {
			var notification = new AchievedNotification(name(achievement), reward(achievement));
			notification.addEventListener(
				AchievedNotification.OK_BUTTON_CLICKED, 
				function (e : Event) { _stage.removeChild(notification); }
			);
			_stage.addChild(notification);
		}
	}
}